package com.teacher.hong.servlet.student;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.bean.Page;
import com.teacher.hong.entity.Student;
import com.teacher.hong.service.IClazzService;
import com.teacher.hong.service.IStudentService;
import com.teacher.hong.service.impl.ClazzServiceImpl;
import com.teacher.hong.service.impl.StudentServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 学生新增/修改接口
 */
//@WebServlet("/student/edit")
public class StudentEditServlet extends HttpServlet {

    IStudentService studentService;
    IClazzService clazzService;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        studentService = context.getBean("studentService", StudentServiceImpl.class);
        clazzService = context.getBean("clazzService", ClazzServiceImpl.class);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //接收各种参数
        Integer id = req.getParameter("id") == null ? null : Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        Integer classId = Integer.parseInt(req.getParameter("clazzId"));
        String sex = req.getParameter("sex");
        Short age = Short.parseShort(req.getParameter("age"));
        String address = req.getParameter("address");

        //根据接收到的参数，实例一个学生对象
        Student student = new Student(id, name, classId, sex, age, address);
        //调用studentService.save方法，并返回其结果给success变量
        boolean success = studentService.save(student);

        JSONObject object = new JSONObject(true);
        object.put("state", success ? 200 : 600);
        object.put("message", success ? "success" : "fail, 未找到对应ID的学生");
        object.put("timestamp", LocalDateTime.now());

        resp.setStatus(success ? 200 : 600);

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(object.toJSONString());
    }
}
